package com.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.alibaba.fastjson.JSON;
import com.demo.common.dto.JuHeDto;
import com.demo.common.dto.StockReturnDto;
import com.demo.common.model.Stock;
import com.demo.common.model.Stockinfo;
import com.demo.common.model.Stocksignal;

public class HttpUtil {

	public static Document getDocumentByGet(String url) throws Exception {
		return Jsoup.connect(url).userAgent("Mozilla").timeout(10000).get();
	}
	
	public static boolean getStockInfoList(String[] stockCodes, List<Stockinfo> stockInfoList, List<Stocksignal> stockSignalList) {
		StringBuffer codeBuf = new StringBuffer();
		for (int i = 0; i < stockCodes.length; i++) {
			codeBuf.append(stockCodes[i])
				   .append(",");
		}
		String httpArg = "stockid=" + codeBuf.substring(0, codeBuf.length()-2) + "&list=1";
		System.out.println("请求url:http://apis.baidu.com/apistore/stockservice/stock" + httpArg);
		String resultStr = request("http://apis.baidu.com/apistore/stockservice/stock", httpArg);
		StockReturnDto retData = JSON.parseObject(resultStr, StockReturnDto.class);
		try {
			Thread.sleep(300);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if(0 == retData.getErrNum()) {
			com.demo.common.dto.Stockinfo[] dto = retData.getRetData().getStockinfo();
			for (com.demo.common.dto.Stockinfo stockinfo : dto) {
				Stockinfo tmp = new Stockinfo();
				
				BigDecimal openningPrice = stockinfo.getOpenningPrice();
				BigDecimal currentPrice = stockinfo.getCurrentPrice();
				BigDecimal hPrice = stockinfo.gethPrice();
				BigDecimal lPrice = stockinfo.getlPrice();
				if(openningPrice.compareTo(new BigDecimal(0)) > 0 &&
						currentPrice.compareTo(new BigDecimal(0)) > 0 &&
						hPrice.compareTo(new BigDecimal(0)) > 0 &&
						lPrice.compareTo(new BigDecimal(0)) > 0) {
					tmp.setStockCode(stockinfo.getCode());
					tmp.setDate(stockinfo.getDate());//数据时间
					tmp.setTime(stockinfo.getTime());//具体时间
					tmp.setOpenningPrice(openningPrice);//开盘价
					tmp.setCurrentPrice(currentPrice);
					tmp.setHPrice(hPrice);//今日最高价
					tmp.setLPrice(lPrice);//今日最低价
					stockInfoList.add(tmp);
					
					//判断是否有交易信号
					BigDecimal x = hPrice.subtract(lPrice);
					if(x.compareTo(new BigDecimal(0)) > 0) {
						BigDecimal st = openningPrice.subtract(currentPrice).abs();
						BigDecimal _H;
						BigDecimal _L;
						if(st.multiply(new BigDecimal(5)).compareTo(x) <= 0) {
							Stocksignal stocksignal = new Stocksignal();
							//stocksignal.setSignalDate(new Date());
							stocksignal.setDailyChar(stockinfo.getDayurl());
							stocksignal.setStockCode(stockinfo.getCode());
							BigDecimal weight = new BigDecimal(0);
							if(openningPrice.compareTo(currentPrice) > 0) {
								_H = openningPrice;
								_L = currentPrice;
							} else {
								_H = currentPrice;
								_L = openningPrice;
							}
							BigDecimal y = hPrice.subtract(_H);//上影线
							BigDecimal z = _L.subtract(lPrice);//下影线
							if(z.divide(x, 2).compareTo(new BigDecimal(0.75)) >= 0) {
								weight = z.divide(x, 2);
								stocksignal.setSignalType(Stocksignal.TYPE_BUY);
							} else if (y.divide(x, 2).compareTo(new BigDecimal(0.75)) > 0) {
								weight = y.divide(x, 2);
								stocksignal.setSignalType(Stocksignal.TYPE_SELL);
							} else {
								continue;
							}
							stocksignal.setWeight(weight);
							stockSignalList.add(stocksignal);
						}
					}
				}
			}
		} else {
			
		}
		return true;
	}
	
	/**
	 * 
	 * @param key 聚合申请的key
	 * @param page 第几页,默认第1页
	 * @param type 每页返回条数,1(20条默认),2(40条),3(60条),4(80条)
	 * @param readTimeOut 读取最长时间
	 * @param connectionTimeOut 连接最大时间
	 * @return
	 * @throws IOException 
	 */
	public static String getStockInfoFromJuHe(String httpUrl, String key, int page, int type, Integer readTimeOut, Integer connectionTimeOut) throws IOException {
		BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();
	    httpUrl = httpUrl + "?key=" + key + "&page=" + page + "&type=" + type;
	    
        URL url = new URL(httpUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        
        if(null != readTimeOut) {
        	connection.setReadTimeout(readTimeOut);
        }
        
        if(null != connectionTimeOut) {
        	connection.setConnectTimeout(connectionTimeOut);
        }
        
        // 填入apikey到HTTP header
        //connection.setRequestProperty("apikey",  "720589e49d98af788ece529de8e8ab36");
        connection.connect();
        InputStream is = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String strRead = null;
        while ((strRead = reader.readLine()) != null) {
            sbf.append(strRead);
            sbf.append("\r\n");
        }
        reader.close();
        result = sbf.toString();
	   
	    return result;
	}
	
	/**
	 * @param urlAll
	 *            :请求接口
	 * @param httpArg
	 *            :参数
	 * @return 返回结果
	 */
	public static String request(String httpUrl, String httpArg) {
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();
	    httpUrl = httpUrl + "?" + httpArg;

	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url
	                .openConnection();
	        connection.setRequestMethod("GET");
	        
	        // 填入apikey到HTTP header
	        connection.setRequestProperty("apikey",  "720589e49d98af788ece529de8e8ab36");
	        connection.connect();
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return result;
	}
	
	public static void main(String[] args) {
		//String jsonStr = request("http://apis.baidu.com/apistore/stockservice/stock", "stockid=sh512500,sh512110,sh512120,sh512210,sh512220,sh512230,sh512300,sh512310,sh512330,sh51234&list=1");
		//StockReturnDto retData = JSON.parseObject(jsonStr, StockReturnDto.class);
		//System.out.println(request("http://apis.baidu.com/apistore/stockservice/stock", "stockid=sh900933,sh201010&list=1"));
		String jsonStr;
		try {
			jsonStr = getStockInfoFromJuHe("http://web.juhe.cn:8080/finance/stock/shall", "411efa889d780a4a20130b988caca4bb", 1, 1, 3000, 3000);
			System.out.println(jsonStr);
			JuHeDto jhDto = JSON.parseObject(jsonStr, JuHeDto.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
